package one.three.fortySeven;

public class Queue<Item> {
	private Node first;
	private Node last;
	private int N;

	private class Node {
		Item item;
		Node next;
	}

	public boolean isEmpty() {
		return first == null;
	}

	public int size() {
		return N;
	}

	public void enqueue(Item item) {
		Node oldFast = last;
		last = new Node();
		last.item = item;
		last.next = null;
		if (isEmpty())
			first = last;
		else
			oldFast.next = last;
		N++;
	}

	public Item dequeue() {
		Item item = first.item;
		first = first.next;
		if (isEmpty())
			last = null;
		N--;
		return item;
	}

	@Override
	public String toString() {
		StringBuilder s = new StringBuilder();
		Node c = first;
		while (c != null) {
			s.append("[" + c.item + "]");
			c = c.next;
		}
		return s.toString();
	}

	public Queue<Item> catenation(Queue<Item> q1, Queue<Item> q2) {
		if (q1 != null && q2 != null) {
			Item[] a1 = (Item[]) new Object[q1.N];
			Item[] a2 = (Item[]) new Object[q2.N];
			Queue<Item> r = new Queue<Item>();
			for (int i = 0; i < a1.length; i++) {
				r.enqueue(q1.dequeue());// a1[i] = q1.dequeue();
			}
			for (int i = 0; i < a2.length; i++) {
				r.enqueue(q2.dequeue()); // a2[i] = q2.dequeue();
			}

			return r;
		}
		return q1 == null ? q2 : q1;
	}

	public static void main(String[] args) {
		Queue<String> q1 = new Queue<String>();
		q1.enqueue("a");
		q1.enqueue("b");
		Queue<String> q2 = new Queue<String>();
		q2.enqueue("c");
		q2.enqueue("d");

		System.out.println(q1);
		System.out.println(q2);

		Queue<String> r = q1.catenation(q1, q2);
		System.out.println(r);
	}
}
